import isFunction from "./isFunction";
import isFunctionComponent from "./isFunctionComponent";
import mountNativeElement from "./mountNativeElement";
export default function mountComponent(virtualDOM, container, oldDOM) {
  let nextVirtualDOM = null;

  let component = null;

  // 类组件 VS 函数组件
  if (isFunctionComponent(virtualDOM)) {
    console.log("函数组件");
    nextVirtualDOM = buildFunctionComponent(virtualDOM);
  } else {
    console.log("类组件");
    nextVirtualDOM = buildClassComponent(virtualDOM);
    component = nextVirtualDOM.component;
  }

  if (isFunction(nextVirtualDOM)) {
    // 组件
    mountComponent(nextVirtualDOM, container, oldDOM);
  } else {
    // DOM元素
    mountNativeElement(nextVirtualDOM, container, oldDOM);
  }

  if(component) {
    // 生命周期函数-组件挂载后调用
    component.componentDidMount();
    if(component.props && component.props.ref) {
      component.props.ref(component)
    }
  }
}

function buildFunctionComponent(virtualDOM) {
  // 函数组件
  return virtualDOM.type(virtualDOM.props || {});
}

function buildClassComponent(virtualDOM) {
  // 类组件
  const component = new virtualDOM.type(virtualDOM.props || {});
  const nextVirtualDOM = component.render();
  // 挂载实例对象
  nextVirtualDOM.component = component;
  return nextVirtualDOM;
}
